﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using NetDisk_WebService.Common;
using Newtonsoft.Json;
using System.Text;


namespace NetDisk_WebService
{
    public partial class UploadFileSingle : System.Web.UI.Page
    {
        BLL.NetDisk netDiskBLL = new BLL.NetDisk();
        protected void Page_Load(object sender, EventArgs e)
        {
            ReceiveFile();

        }


        /// <summary> 
        /// Process the web response. 
        /// </summary> 
        /// <param name="webRequest">The request object.</param> 
        /// <returns>The response data.</returns> 
        public string ReceiveFile()
        {
            string returnValue = "";
            bool isSuccess = true;

            int fileSize = 0;
            bool IsCreate = true;
            string TempFileName = "";
            bool IsEnd = true;
            string DestID = "";
            string DestPath = "";
            string JsonNetDiskModel = "";
            bool IsCancel = false;
            Model.NetDisk netDiskModel = null;

            //先获取参数
            if (isSuccess)
            {
                try
                {
                    fileSize = int.Parse(System.Web.HttpContext.Current.Request.Headers["FileSize"].ToString());
                    IsCreate = bool.Parse(System.Web.HttpContext.Current.Request.Headers["IsCreate"].ToString());
                    TempFileName = HttpUtility.UrlDecode(System.Web.HttpContext.Current.Request.Headers["TempFileName"].ToString());
                    IsEnd = bool.Parse(System.Web.HttpContext.Current.Request.Headers["IsEnd"].ToString());
                    DestID = HttpUtility.UrlDecode(System.Web.HttpContext.Current.Request.Headers["DestID"].ToString());
                    JsonNetDiskModel = HttpUtility.UrlDecode(System.Web.HttpContext.Current.Request.Headers["JsonNetDiskModel"].ToString());
                    IsCancel = bool.Parse(System.Web.HttpContext.Current.Request.Headers["IsCancel"].ToString());
                }
                catch (Exception ex)
                {
                    isSuccess = false;
                    returnValue = ex.ToString();
                }
            }

            if (isSuccess)
            {
                if (IsCancel)//取消，删除当前文件
                {
                    try
                    {
                        //为了使httpwebRequest能够正常返回接收信息，添加下句，接收的数据无任何作用。
                        byte[] readBuffer = System.Web.HttpContext.Current.Request.BinaryRead(fileSize);


                        serverIO.DelFile(TempFileName);
                        returnValue = "cancelSuccess";
                    }
                    catch (Exception ex)
                    {
                        isSuccess = false;
                        returnValue = ex.ToString();
                    }
                }
                else//未取消，继续程序
                {
                    //发送数据
                    if (isSuccess)
                    {
                        try
                        {


                            byte[] readBuffer = System.Web.HttpContext.Current.Request.BinaryRead(fileSize);

                            FileStream destStream;
                            if (IsCreate)
                            {
                                destStream = new FileStream(TempFileName, FileMode.Create);
                            }
                            else
                            {
                                destStream = new FileStream(TempFileName, FileMode.Append);
                            }
                            destStream.Write(readBuffer, 0, readBuffer.Length);  //二进制转换成文件

                            destStream.Close();



                            returnValue = "success";
                        }
                        catch (Exception ex)
                        {
                            isSuccess = false;
                            returnValue = ex.ToString();
                        }
                    }
                    //复制文件
                    if (isSuccess)
                    {
                        try
                        {
                            if (IsEnd)//最后一段，复制到真实目录，且添加数据
                            {
                                //获取数据
                                netDiskModel = JsonConvert.DeserializeObject<Model.NetDisk>(JsonNetDiskModel);


                                //根据DestID获取DestPath
                                string NetDiskDir = System.Configuration.ConfigurationManager.AppSettings["NetDiskDir"];
                                //父级文件夹路径
                                NetDiskService netDiskServiceBLL = new NetDiskService();
                                string parentPath = netDiskServiceBLL.GetPathByPid(DestID.ToString()) + "\\";
                                DestPath = NetDiskDir;
                                if (parentPath != "")
                                {
                                    DestPath += parentPath;
                                }
                                DestPath += netDiskModel.FName;
                                serverIO.MoveFile(TempFileName, DestPath);
                            }
                        }
                        catch (Exception ex)
                        {
                            isSuccess = false;
                            returnValue = ex.ToString();
                        }
                    }
                    //插入数据
                    if (isSuccess)
                    {
                        try
                        {
                            if (IsEnd)//最后一段，复制到真实目录，且添加数据
                            {
                                FileStream readStream = new FileStream(DestPath, FileMode.Open, FileAccess.Read);
                                netDiskModel.FEntityNo = GlobalConstant.ENTITYNO;
                                netDiskModel.FSize = readStream.Length;
                                netDiskModel.FMD5 = GetMD5HashFromFile(readStream);
                                readStream.Close();
                                netDiskBLL.AddNetDiskCover(netDiskModel);
                                
                            }
                        }
                        catch (Exception ex)
                        {
                            isSuccess = false;
                            returnValue = ex.ToString();
                        }
                    }

                }
            }

            return returnValue;
        }



        /// <summary>
        /// 计算文件的MD5校验
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private string GetMD5HashFromFile(Stream file)
        {
            try
            {
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }

    }
}